package Bench::Test::View;

use 5.008004;
use strict;
use warnings;
use Switch;
use Storable qw(dclone);

use Bench::Test::View::HTML;
use Bench::Test::View::XML;
use Bench::Test::View::Latex;
use Bench::Test::View::Text;

#============================================================================== 
# Object Constructor.
#============================================================================== 
sub new {
   my ($class, %params) = @_;
   
   my $format = $params{format};

   if ($format) {
      $format =~ /text|html|xml|latex|file:(.*)/
         or die 'Format not supported. Try "text", ' . 
                 '"html", "xml", "latex" or "file:yourtemplate.tt"';
   }

   my $verbose = (defined $params{verbose} ? $params{verbose} : 1);

   return bless {
                   VERBOSE  => $verbose,
                   FORMAT   => $format,
                   TEMPLATE => $1,
                   DATA     => [],
                }, $class;
}

sub set_format {
   my ($self, $format) = (shift, shift);

   $format =~ /text|html|xml|latex|file:(.*)/
      or die 'Format not supported. Try "text", ' . 
             '"html", "xml" "latex" or "file:yourtemplate.tt"';

   $self->{FORMAT}   = $format;
   $self->{TEMPLATE} = $1;
}

sub add_row {
   my ($self, $row) = @_;
   push @{$self->{DATA}}, $row;

   return unless ($self->{VERBOSE});

   print "$_\t" for (@$row);
   print "\n";
}

sub process_user_template {
   my $self = shift;

   my $output;
   my $tt_file = $self->{TEMPLATE};

   die "An error ocurred when trying to open templet file: $tt_file\n"
      unless (-r $tt_file);

   my $config = {
      INTERPOLATE => 1,  # expand "$var" in plain text
      POST_CHOMP  => 0,  # cleanup whitespace
      PRE_CHOMP   => 0,
      EVAL_PERL   => 1,  # evaluate Perl code blocks
      ABSOLUTE    => 1,  # Allow absolute file path
   };

   my $template = Template->new($config);
   my $vars = { data => dclone($self->{DATA}) };

   $template->process($tt_file, $vars, \$output)
      || die $template->error();

   return $output;
}

sub process {
   my ($self, $format) = @_;

   $self->set_format($format) if ($format);

   return $self->process_user_template if ($self->{TEMPLATE});

   my $output;
   switch ($self->{FORMAT}) {
      case 'xml'   { $output = Bench::Test::View::XML::process  ( dclone($self->{DATA}) ) }
      case 'text'  { $output = Bench::Test::View::Text::process ( dclone($self->{DATA}) ) }
      case 'html'  { $output = Bench::Test::View::HTML::process ( dclone($self->{DATA}) ) }
      case 'latex' { $output = Bench::Test::View::Latex::process( dclone($self->{DATA}) ) }
   }
   return $output;
}

1;
